package com.biz.service.api;

import com.biz.model.Pmodel.weixin.AccessToken;
import com.biz.model.Singleton.ZkNode;
import com.framework.dao.mdao.DaoSupport;
import com.framework.utils.ConfigUtil;
import com.framework.utils.Tools;
import com.framework.utils.UuidUtil;
import com.framework.utils.weixin.EnumMethod;
import com.framework.utils.weixin.HttpRequestUtil;
import com.framework.utils.weixin.WechatAccessToken;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lzq on 2017/2/9.
 */
@Service("wxUtilService")
public class WxUtilServiceImpl  implements WxUtilServiceI {

    @Resource(name = "daoSupport")
    private DaoSupport dao;


    /**
     * 获取AccessToken(本地)
     *
     * @return
     */
    @Override
    public String getAccessToken_bd() throws Exception {
        String tolen="";
        //本地token
        tolen=get_Ben_Di_token();
        return tolen;
    }


    private String get_Ben_Di_token(){
        String newAccessToken = "";
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = (Map<String, Object>)dao.findForObject("WxUtilDao.getWxTicketById", null);
        } catch (Exception e) {

        }
        if(map == null )
        {
            newAccessToken = reloadAccessToken("", "1").getToken();
        }else if(map !=null && map.get("ACCESS_TOKEN") == null){
            newAccessToken = reloadAccessToken((String) map.get("id"), "0").getToken();
        }else if(map !=null && map.get("ACCESS_TOKEN") != null){
            String accessTokenStr = (String) map.get("ACCESS_TOKEN");
            if (Tools.isEmpty(accessTokenStr))
            {
                System.out
                        .println("################################################");
                System.out.println("载入JsApiTicket已超时，重新载入");
                System.out
                        .println("################################################");
                newAccessToken = reloadAccessToken((String) map.get("id"), "0").getToken();
            }
            else
            {
                String[] accessTokenArg = accessTokenStr.split(",");
                long nowTime = new Date().getTime();
                long putTime=0,diffTime=0;
                if(accessTokenArg[1]!=null){
                    putTime = Long.parseLong(accessTokenArg[1]);
                }
                if(accessTokenArg[2]!=null){
                    diffTime = Long.parseLong(accessTokenArg[2]);
                }
                if (Math.abs(nowTime - putTime) >= diffTime)
                {
                    System.out
                            .println("################################################");
                    System.out.println("载入token已超时，重新载入");
                    System.out
                            .println("################################################");
                    newAccessToken = reloadAccessToken((String) map.get("id"),"0").getToken();
                }
                if(!select_accessToken(accessTokenArg[0]))//是否有效
                {
                    System.out.println("载入JsApiTicket已超时，重新载入");
                    newAccessToken = reloadAccessToken((String) map.get("id"),"0").getToken();
                }
                else
                {
                    newAccessToken = accessTokenArg[0];
                }
            }
        }

        return newAccessToken;
    }

    /**
     * 重新装载AccessToken
     *
     * @return
     */
    public AccessToken reloadAccessToken(String id, String type)
    {
        AccessToken accessToken = WechatAccessToken.getAccessToken(ConfigUtil.get("appId"),
                ConfigUtil.get("appSecret"));
        Map<String, String> map = new HashMap<String, String>();
        if("1".equals(type)){
            map.put("id", UuidUtil.get32UUID());
        }else{
            map.put("id", id);
        }
        map.put("ACCESS_TOKEN", accessToken.getToken() + ","
                + new Date().getTime() + "," + (accessToken.getExpiresIn() * 1000));
        try {
            if("1".equals(type))//添加
            {
                dao.save("WxUtilDao.saveAccessToken",map);
            }else{
                dao.update("WxUtilDao.updateAccessToken",map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }




    /**
     * 验证accessToken是否有效
     * @param accessToken true:有效 false：无效
     * @return
     */
    public boolean select_accessToken(String accessToken)
    {
        try
        {
            String ip_list="";
            //空
            if(Tools.isEmpty(accessToken))
            {
                return false;
            }
            //获取微信服务器IP地址，目前用于验证access_token是否有效
            String select_access_token_url="https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=ACCESS_TOKEN";

            String requestUrl = select_access_token_url.replace("ACCESS_TOKEN", accessToken);

            JSONObject jsonObject = HttpRequestUtil.httpRequest(requestUrl,
                    EnumMethod.GET.name(), null);
            if (jsonObject == null)
            {
                jsonObject = HttpRequestUtil.httpRequest(requestUrl,
                        EnumMethod.GET.name(), null);
            }
            // 如果请求成功
            if (null != jsonObject)
            {
                try
                {
                    ip_list=jsonObject.getString("ip_list").toString();

                } catch (JSONException e)
                {
                    ip_list = null;
                }
            }

            if(Tools.isEmpty(ip_list))
            {
                return false;
            }
            else
            {
                return true;
            }

        } catch (Exception e)
        {
            return false;
        }

    }



}
